<template>
  <div class="user-management">
    <el-card class="user-table-card">
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <el-button type="primary" @click="handleAddUser">新增用户</el-button>
        </div>
      </template>
      
      <el-table :data="userList" style="width: 100%" border>
        <el-table-column prop="operatorId" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="150" />
        <el-table-column prop="realName" label="姓名" />
        <el-table-column prop="role" label="角色" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.role === 'ADMIN' ? 'danger' : 'primary'">
              {{ scope.row.role === 'ADMIN' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="active" label="是否活跃" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.active ? 'success' : 'info'">
              {{ scope.row.active ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLogin" label="最后登录时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.lastLogin) }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建日期" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="updatedAt" label="修改日期" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.updatedAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <!-- 只有当前用户为管理员(operatorId=1)时才能编辑其他用户 -->
            <el-button size="small" @click="handleEditUser(scope.row)" :disabled="!isCurrentUserAdmin && scope.row.operatorId == 1">修改</el-button>
            <!-- 只有当前用户为管理员(operatorId=1)时才能删除其他用户 -->
            <el-button size="small" v-if="scope.row.operatorId != 1 || isCurrentUserAdmin" type="danger" @click="handleDeleteUser(scope.row)" :disabled="scope.row.operatorId == 1">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 用户编辑/新增对话框 -->
    <el-dialog
      :model-value="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="userFormRef"
        :model="currentUser"
        :rules="userFormRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="currentUser.username" :disabled="!isAddMode" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="currentUser.password" type="password" />
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="currentUser.realName" :disabled="!isCurrentUserAdmin && currentUser.operatorId == 1" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="currentUser.role" placeholder="请选择角色" :disabled="!isCurrentUserAdmin && currentUser.operatorId == 1">
            <el-option label="管理员" value="ADMIN" />
            <el-option label="普通用户" value="USER" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否活跃" prop="active">
          <el-switch v-model="currentUser.active" :disabled="!isCurrentUserAdmin && currentUser.operatorId == 1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmitUser" :disabled="!isCurrentUserAdmin && currentUser.operatorId == 1">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getOperators, 
  createOperator, 
  getOperatorById, 
  updateOperator, 
  deleteOperator 
} from '@/api/auth'
import { useUserStore } from '@/stores/user'
import { formatDateTime } from '@/utils/timeUtil'

// 用户数据类型定义
interface User {
  operatorId: number
  username: string
  password?: string
  realName: string
  role: string
  active: boolean
  isActive?: boolean // Added isActive property
  lastLogin: string
  createdAt: string
  updatedAt: string
}

// 用户列表数据
const userList = ref<User[]>([])

// 分页相关数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框相关数据
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isAddMode = ref(false)

// 当前用户信息
const userStore = useUserStore()
const isCurrentUserAdmin = computed(() => {
  return userStore.userInfo?.userId === 1
})

// 当前编辑的用户
const currentUser = reactive<User>({
  operatorId: 0,
  username: '',
  password: '',
  realName: '',
  role: 'USER',
  active: true,
  lastLogin: '',
  createdAt: '',
  updatedAt: ''
})

// 表单引用
const userFormRef = ref()

// 表单验证规则
const userFormRules = {
  username: [
    { required: true, message: '请输入登录用户名', trigger: 'blur' }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        // 编辑模式下密码非必填
        if (!isAddMode.value && !value) {
          return callback()
        }
        if (!value) {
          return callback(new Error('请输入密码'))
        }
        callback()
      }
    }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 获取当前用户信息

// 获取用户列表
const fetchUsers = async () => {
  try {
    const response = await getOperators({
      page: currentPage.value - 1,
      size: pageSize.value
    })
    if (!response) return
    userList.value = response.content.map((user: User) => ({
      ...user,
      id: user.operatorId  // 保持与之前代码的兼容性
    }))
    total.value = response.totalElements || 0
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  }
}

// 处理新增用户
const handleAddUser = () => {
  // 检查权限
  
  isAddMode.value = true
  dialogTitle.value = '新增用户'
  // 重置表单数据
  Object.assign(currentUser, {
    operatorId: 0,
    username: '',
    password: '',
    realName: '',
    role: 'USER',
    active: true
  })
  dialogVisible.value = true
}

// 处理编辑用户
const handleEditUser = async (user: User) => {
  // 检查权限
  if (!isCurrentUserAdmin.value && user.operatorId == 1) {
    ElMessage.error('只有管理员才能编辑管理员账户')
    return
  }
  
  try {
    isAddMode.value = false
    dialogTitle.value = '编辑用户'
    // 获取用户详情
    const response = await getOperatorById(user.operatorId)
    Object.assign(currentUser, { ...response, password: '' })
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取用户详情失败')
  }
}

// 处理删除用户
const handleDeleteUser = (user: User) => {
  // 检查权限
  if (user.operatorId == 1) {
    ElMessage.error('管理员账户不允许删除！')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除用户 "${user.username}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    // 执行删除操作
    try {
      await deleteOperator(user.operatorId)
      await fetchUsers() // 重新获取用户列表
      ElMessage.success('删除成功')
    } catch (error) {
      ElMessage.error('删除用户失败')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 处理对话框关闭
const handleDialogClose = () => {
  dialogVisible.value = false
  userFormRef.value?.resetFields()
}

// 处理提交用户（新增或修改）
const handleSubmitUser = () => {
  // 检查权限
  if (!isCurrentUserAdmin.value && currentUser.operatorId == 1) {
    ElMessage.error('只有管理员才能修改管理员账户')
    return
  }
  
  userFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      const now = new Date().toLocaleString()
      
      try {
        if (isAddMode.value) {
          // 新增用户
          const { password, operatorId, ...userData } = currentUser
          // 同时传 isActive 和 active，且数据一致
          userData.isActive = userData.active
          await createOperator({ ...userData, password })
          ElMessage.success('新增用户成功')
        } else {
          // 修改用户 - 移除用户名字段，因为不允许修改
          const { operatorId, ...userData } = currentUser
          // 如果密码为空，则不更新密码
          if (!userData.password) {
            delete userData.password
          }
          // 同时传 isActive 和 active，且数据一致
          userData.isActive = userData.active
          await updateOperator(operatorId, userData)
          ElMessage.success('修改用户成功')
        }
        
        dialogVisible.value = false
        await fetchUsers() // 重新获取用户列表
      } catch (error) {
        ElMessage.error(isAddMode.value ? '新增用户失败' : '修改用户失败')
      }
    }
  })
}

// 分页相关处理函数
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchUsers()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchUsers()
}

// 组件挂载时执行
onMounted(() => {
  // 检查用户是否已登录，如果未登录则不发起请求
  if (userStore.userInfo) {
    fetchUsers()
  }
})
</script>

<style scoped>

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
